package com.bojiu.lawsearch.lawsearch.controller;

import com.bojiu.lawsearch.lawsearch.model.Attachment;
import com.bojiu.lawsearch.lawsearch.util.Constances;
import com.bojiu.lawsearch.lawsearch.util.FileHandler;
import com.bojiu.lawsearch.lawsearch.util.JsonResult;
import com.bojiu.lawsearch.lawsearch.util.ResultCode;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author afdiao
 * @Date 2020/2/26 22:39
 */
@Api(description = "文件操作接口，功能已完成！！！")
@RestController
@RequestMapping("file")
@Slf4j
public class FileController {
    @Autowired
    FileHandler fileHandler;

    @ApiOperation(value = "解析word", notes = "上传word解析成excel，返回excel的链接提供下载")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = String.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口"),
            @ApiResponse(code = 1000, message = "读取word失败"),
            @ApiResponse(code = 1100, message = "创建excel失败"),
    })
    @PostMapping("handleword")
    public String handleWord(@RequestParam("file") MultipartFile multipartFile) {
        log.debug("开始上传word");
        String readWord = fileHandler.readWord(multipartFile);
        if ("error".equals(readWord)) {
            return new Gson().toJson(new JsonResult(ResultCode.ERRORWORD));
        }
        try {
            String excel = fileHandler.createExcel(readWord);
            return new Gson().toJson(new JsonResult(ResultCode.SUCCESS, Constances.WEB_URL + excel));
        } catch (Exception e) {
            log.error("error to create excel,error is :{}", e);
            return new Gson().toJson(new JsonResult(ResultCode.ERRORCREATEEXCEL));
        }
    }

    /**
     * 处理上传文件
     *
     * @param multipartFile
     * @return
     */
    @ApiOperation(value = "上传文件", notes = "上传文件，返回文件存储名")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = String.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口"),
            @ApiResponse(code = 100, message = "请求失败")
    })
    @PostMapping("uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        try {
            Attachment file = fileHandler.createFile(multipartFile);
            return new Gson().toJson(new JsonResult(ResultCode.SUCCESS, file.getStoreName()));
        } catch (Exception e) {
            log.error("error to create file");
            return new Gson().toJson(new JsonResult(ResultCode.FAIL));
        }
    }
}
